package cn.leshua.service;

import cn.leshua.config.MerchantConfig;
import cn.leshua.util.ReqSerialNoUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * Description:商户进件相关接口
 * Author:Geno
 * Date:2018/5/18
 * Mail:geno@yeahka.com
 */
public class MerchantGateWayService {
//    private static String AGENT_ID = "10";//代理商编号
//    private static String KEY = "17B10781A8C5178870197906F71749D8";//私钥
//    private static String VERSION = "1.0";//版本号
//    private static String CHARSET = "UTF-8";//字符编码
//    private static String REQ_SERIAL_NO = UUID.randomUUID().toString();//请求流水号，可自定义

//    private static String REGISTER_URL = "http://pos.lepass.cn/api/merchant/register.do";//商户进件
//    private static String OPEN_URL = "http://pos.lepass.cn/api/merchant/open.do";//商户开通业务
//    private static String UPDATE_URL = "http://pos.lepass.cn/api/merchant/update.do";//商户信息修改
//    private static String GET_URL = "http://pos.lepass.cn/api/merchant/get.do";//查询商户信息
//    private static String CHILD_REGISTER_URL = "http://pos.lepass.cn/api/merchant/sonMerchantRegister.do";//子商户开通
//    private static String BELONG_URL = "http://pos.lepass.cn/api/merchant/belong.do";//商户归属查询


    private static CloseableHttpClient httpclient = HttpClients.createDefault();
    private Logger logger = LoggerFactory.getLogger(getClass());


    public String downDzd(JSONObject data) {
        return requestApi(MerchantConfig.DOWNLOAD_URL, data);

    }

    /**
     * m
     * 商户进件
     *
     * @param data
     * @return
     */
    public String register(JSONObject data) {
        return requestApi(MerchantConfig.REGISTER_URL, data);
    }

    /**
     * 商户开通业务
     *
     * @param data
     * @return
     */
    public String open(JSONObject data) {
        return requestApi(MerchantConfig.OPEN_URL, data);
    }


    /**
     * 商户信息修改
     *
     * @param data
     * @return
     */
    public String update(JSONObject data) {
        return requestApi(MerchantConfig.UPDATE_URL, data);
    }


    /**
     * 查询商户信息
     *
     * @param data
     * @return
     */
    public String get(JSONObject data) {
        return requestApi(MerchantConfig.GET_URL, data);
    }


    /**
     * 审核状态查询
     *
     * @param data
     * @return
     */
    public String auditQuery(JSONObject data) {
        return requestApi(MerchantConfig.AUDIT_QUERY_RUL, data);
    }

    /**
     * 微信参数配置
     *
     * @param data
     * @return
     */
    public String wxConfig(JSONObject data) {
        return requestApi(MerchantConfig.WX_CONFIG_URL, data);
    }

    /**
     * 微信配置参数查询
     *
     * @param data
     * @return
     */
    public String wxConfigQry(JSONObject data) {
        return requestApi(MerchantConfig.WX_CONFIG_QRY_URL, data);
    }


    /**
     * 调用请求
     *
     * @param url  地址
     * @param data 数据
     * @return
     */
    private String requestApi(String url, JSONObject data) {
        return requestApi(url, data, null);
    }

    public String uploadPicApi(File file) {
        Map<String, File> map = new HashMap<String, File>();
        JSONObject data = new JSONObject();

        String myMD5 = null;
        try {
            myMD5 = DigestUtils.md5Hex(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        data.put("fileMD5", myMD5);
        map.put("media", file);

        return requestApi(MerchantConfig.PIC_UPLOAD_RUL, data, map);
    }


    /**
     * 调用请求
     *
     * @param url      地址
     * @param data     数据
     * @param pictures 图片
     * @return
     */
    private String requestApi(String url, JSONObject data, Map<String, File> pictures) {
        logger.info("请求地址:{}", url);
        logger.info("请求参数:{}", data);
        String sign = getSign(data);//获取签名值
        String result = "";
        HttpPost httppost = new HttpPost(url);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntityBuilder.setCharset(Charset.forName(MerchantConfig.CHARSET));
        multipartEntityBuilder.addPart("agentId", new StringBody(MerchantConfig.AGENT_ID, ContentType.APPLICATION_JSON));//代理商编号
        multipartEntityBuilder.addPart("version", new StringBody(MerchantConfig.VERSION, ContentType.APPLICATION_JSON));//版本
        multipartEntityBuilder.addPart("reqSerialNo", new StringBody(ReqSerialNoUtil.getReqSerialNo(), ContentType.APPLICATION_JSON));//请求流水号
        multipartEntityBuilder.addPart("data", new StringBody(data.toJSONString(), ContentType.APPLICATION_JSON));//数据内容
        multipartEntityBuilder.addPart("sign", new StringBody(sign, ContentType.APPLICATION_JSON));//签名值
        //图片文件
        if (pictures != null) {
            for (String picName : pictures.keySet()) {
                multipartEntityBuilder.addPart(picName, new FileBody(pictures.get(picName)));
            }
        }
        HttpEntity reqEntity = multipartEntityBuilder.build();
        httppost.setEntity(reqEntity);
        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        } catch (IOException e) {
            logger.error("Exception:{}", e);
        }
        logger.info("返回参数:{}", result);
        return result;
    }

    /**
     * 获取签名值
     *
     * @param agentId
     * @param data
     * @return
     */
    private String getSign(JSONObject data) {
        String sign = "";
        String jsonData = data.toJSONString();
        StringBuffer sb = new StringBuffer("lepos");
        sb.append(MerchantConfig.KEY).append(jsonData);//key每个渠道商不一样
        try {
            String md5 = DigestUtils.md5Hex(sb.toString().getBytes(MerchantConfig.CHARSET));
            sign = Base64.encodeBase64String(md5.getBytes(MerchantConfig.CHARSET));
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception:{}", e);
        }
        logger.info("待签参数:{}", sb.toString());
        logger.info("签名值:{}", sign);
        return sign;
    }
}
